package edu.ua.jCompare;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;

public class SidedRenderer  extends JPanel implements Renderer{

	private String srcText = "";
	private String dstText= "";
	
	
	private JTextArea textArea1, textArea2;
	private JScrollPane scroller1, scroller2;
	private JFrame frame;
	private JSplitPane splitter;
	
	
	private int srcNum = 1;
	private int dstNum = 1;

	
	private void setTexts(){
		textArea1 = new JTextArea(srcText);
		textArea1.setEditable(false);
		
		textArea2 = new JTextArea(dstText);
		textArea2.setEditable(false);	
	}
	
	private void setScrollers() throws Exception{
		if (textArea1 == null || textArea2 == null)
			throw new Exception("texts have not been prepared");
		System.out.println(textArea1.getText());
		
		scroller1 = new JScrollPane(textArea1);
		scroller1.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);

 
		scroller2 = new JScrollPane(textArea2);
		scroller2.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
	}
	
	private void setSplitter() throws Exception{
		if (scroller1 == null || scroller2 == null){
			throw new Exception("scrollers have not been prepared");
		}
		splitter = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
		        scroller1, scroller2);
		splitter.setDividerLocation(170);
		splitter.setContinuousLayout(true);
	}
	
	public void initialize(){
		return;
	}
	
	@Override
	public void finalize(){
		setTexts();
		try{
			setScrollers();
			setSplitter();
		}catch (Exception e){
			System.out.println(e.getMessage());
		}
		frame = new JFrame("Comparing old (left) and new (right) side by side ");
		
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setPreferredSize(new Dimension(400, 400));
        //Display the window.
        frame.pack();
		frame.getContentPane().add(splitter);
		
		frame.setVisible(true);
	}
	
	@Override
	public void renderDeletes(List<String> items) {
		for (String item: items){
			srcText += String.format("%04d\t%s%n", srcNum,item);;
			dstText += "\n";
			srcNum++;
		}
	}

	@Override
	public void renderInserts(List<String> items) {
		for (String item: items){
			dstText += String.format("%04d\t%s%n", dstNum,item);
			srcText += "\n";
			dstNum++;
		}
	}

	@Override
	public void renderMatches(List<String> items) {
		for (String item: items){
			srcText += String.format("%04d\t%s%n", srcNum,item);;
			srcNum++;
		}
		for (String item: items){
			dstText += String.format("%04d\t%s%n", dstNum,item);;
			dstNum++;
		}
	}

}
